Integrating RTK Query with GraphQL and Custom Fetch Logic
RTK Query can be integrated with GraphQL or any custom fetch logic by using a custom baseQuery. Instead of relying on REST-style endpoints, you can define your own query function that sends GraphQL requests or handles special request logic.
1. Using fetchBaseQuery for Simple GraphQL Requests: Pass a static GraphQL query string and variables directly to the body of the request.
2. Creating a Custom baseQuery: Use your own fetch or Axios logic to send requests and handle responses.
3. Wrapping GraphQL Clients (e.g., Apollo, urql): Integrate RTK Query with existing GraphQL client instances to share caching and schema handling.
In this example, RTK Query sends a POST request containing a GraphQL query string in the request body. The hook useGetUsersQuery() automatically handles caching, loading, and error states.
This custom base query gives you full flexibility — allowing you to handle GraphQL operations, custom headers, authentication, or even token refresh logic as needed.
In summary, RTK Query is backend-agnostic. Whether you use REST, GraphQL, or a completely custom fetch implementation, you can adapt it easily by defining the right baseQuery function.